<?php
/**
 * 取消男友请求API
 */
require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../classes/User.php';
require_once '../../classes/Friend.php';

// 检查用户是否登录
if (!isLoggedIn()) {
    echo json_encode(['status' => false, 'message' => '请先登录']);
    exit;
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => false, 'message' => '无效的请求方法']);
    exit;
}

$userId = $_SESSION['user_id'];
$requestId = isset($_POST['request_id']) ? intval($_POST['request_id']) : 0;

// 验证请求ID
if ($requestId <= 0) {
    setFlashMessage('error', '无效的请求ID');
    redirect(SITE_URL . '/views/friend/request.php');
}

// 获取数据库连接
$db = Database::getInstance();

// 检查请求是否存在且是当前用户发送的
$request = $db->fetch(
    "SELECT * FROM friendships WHERE id = ? AND user_id = ? AND status = 'pending'",
    [$requestId, $userId]
);

if (!$request) {
    setFlashMessage('error', '男友请求不存在或无权操作');
    redirect(SITE_URL . '/views/friend/request.php');
}

// 删除男友请求
try {
    $db->query("DELETE FROM friendships WHERE id = ?", [$requestId]);
    setFlashMessage('success', '已取消男友请求');
} catch (Exception $e) {
    setFlashMessage('error', '操作失败，请稍后再试');
}

// 重定向回请求页面
redirect(SITE_URL . '/views/friend/request.php');
?>
